package com.huawei.zyb.taskManager.interfaces.rest;

import com.huawei.zyb.taskManager.application.task.TaskApplicationService;
import com.huawei.zyb.taskManager.application.task.dto.TaskDTO;
import com.huawei.zyb.taskManager.application.task.dto.CreateTaskCommand;
import com.huawei.zyb.taskManager.application.task.dto.UpdateTaskCommand;
import com.huawei.zyb.taskManager.application.task.dto.BatchUpdateTaskCommand;
import com.huawei.zyb.taskManager.application.task.dto.TaskStatisticsDTO;
import com.huawei.zyb.taskManager.domain.task.valueobject.TaskStatus;
import com.huawei.zyb.taskManager.domain.task.valueobject.TaskLevel;
import com.huawei.zyb.taskManager.domain.task.valueobject.TaskPriority;
import com.huawei.zyb.taskManager.domain.shared.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/tasks")
public class TaskRestController {
    
    private final TaskApplicationService taskApplicationService;
    
    @Autowired
    public TaskRestController(TaskApplicationService taskApplicationService) {
        this.taskApplicationService = taskApplicationService;
    }
    
    /**
     * 创建任务
     */
    @PostMapping
    public ResponseEntity<TaskDTO> createTask(@Valid @RequestBody CreateTaskCommand command) {
        try {
            TaskDTO task = taskApplicationService.createTask(command);
            return ResponseEntity.status(HttpStatus.CREATED).body(task);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 根据ID查找任务
     */
    @GetMapping("/{id}")
    public ResponseEntity<TaskDTO> findTaskById(@PathVariable Long id) {
        try {
            TaskDTO task = taskApplicationService.findTaskById(id);
            return ResponseEntity.ok(task);
        } catch (BusinessException | IllegalArgumentException e) {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 更新任务
     */
    @PutMapping("/{id}")
    public ResponseEntity<TaskDTO> updateTask(@PathVariable Long id, @Valid @RequestBody UpdateTaskCommand command) {
        try {
            taskApplicationService.updateTask(id, command);
            TaskDTO task = taskApplicationService.findTaskById(id);
            return ResponseEntity.ok(task);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 删除任务
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTask(@PathVariable Long id) {
        try {
            taskApplicationService.deleteTask(id);
            return ResponseEntity.noContent().build();
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 分配任务
     */
    @PatchMapping("/{id}/assign")
    public ResponseEntity<TaskDTO> assignTask(@PathVariable Long id, @RequestBody Map<String, String> request) {
        try {
            String assigneeId = request.get("assigneeId");
            if (assigneeId == null || assigneeId.trim().isEmpty()) {
                return ResponseEntity.badRequest().build();
            }
            taskApplicationService.assignTask(id, assigneeId);
            TaskDTO task = taskApplicationService.findTaskById(id);
            return ResponseEntity.ok(task);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 开始任务
     */
    @PatchMapping("/{id}/start")
    public ResponseEntity<TaskDTO> startTask(@PathVariable Long id) {
        try {
            taskApplicationService.startTask(id);
            TaskDTO task = taskApplicationService.findTaskById(id);
            return ResponseEntity.ok(task);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 暂停任务
     */
    @PatchMapping("/{id}/pause")
    public ResponseEntity<TaskDTO> pauseTask(@PathVariable Long id) {
        try {
            TaskDTO task = taskApplicationService.pauseTask(id);
            return ResponseEntity.ok(task);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 恢复任务
     */
    @PatchMapping("/{id}/resume")
    public ResponseEntity<TaskDTO> resumeTask(@PathVariable Long id) {
        try {
            TaskDTO task = taskApplicationService.resumeTask(id);
            return ResponseEntity.ok(task);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 完成任务
     */
    @PatchMapping("/{id}/complete")
    public ResponseEntity<TaskDTO> completeTask(@PathVariable Long id) {
        try {
            TaskDTO task = taskApplicationService.completeTask(id);
            return ResponseEntity.ok(task);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 取消任务
     */
    @PatchMapping("/{id}/cancel")
    public ResponseEntity<TaskDTO> cancelTask(@PathVariable Long id) {
        try {
            TaskDTO task = taskApplicationService.cancelTask(id);
            return ResponseEntity.ok(task);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 重新打开任务
     */
    @PatchMapping("/{id}/reopen")
    public ResponseEntity<TaskDTO> reopenTask(@PathVariable Long id) {
        try {
            TaskDTO task = taskApplicationService.reopenTask(id);
            return ResponseEntity.ok(task);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 更新任务进度
     */
    @PatchMapping("/{id}/progress")
    public ResponseEntity<TaskDTO> updateTaskProgress(@PathVariable Long id, @RequestBody Map<String, Object> request) {
        try {
            Object progressObj = request.get("progress");
            if (progressObj == null) {
                return ResponseEntity.badRequest().build();
            }
            
            int progress;
            if (progressObj instanceof Integer) {
                progress = (Integer) progressObj;
            } else if (progressObj instanceof Double) {
                progress = ((Double) progressObj).intValue();
            } else {
                return ResponseEntity.badRequest().build();
            }
            
            if (progress < 0 || progress > 100) {
                return ResponseEntity.badRequest().build();
            }
            
            TaskDTO task = taskApplicationService.updateTaskProgress(id, progress);
            return ResponseEntity.ok(task);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 记录实际工时
     */
    @PostMapping("/{id}/actual-hours")
    public ResponseEntity<?> recordActualHours(@PathVariable Long id, @RequestParam Double hours) {
        try {
            taskApplicationService.recordActualHours(id, hours);
            return ResponseEntity.ok().build();
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 根据需求ID查找任务列表
     */
    @GetMapping("/requirement/{requirementId}")
    public ResponseEntity<List<TaskDTO>> findTasksByRequirementId(@PathVariable Long requirementId) {
        try {
            if (requirementId == null || requirementId <= 0) {
                return ResponseEntity.badRequest().build();
            }
            List<TaskDTO> tasks = taskApplicationService.findTasksByRequirementId(requirementId);
            return ResponseEntity.ok(tasks);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    /**
     * 根据指派人ID查找任务列表
     */
    @GetMapping("/assignee/{assigneeId}")
    public ResponseEntity<List<TaskDTO>> findTasksByAssigneeId(@PathVariable String assigneeId) {
        List<TaskDTO> tasks = taskApplicationService.findTasksByAssigneeId(assigneeId);
        return ResponseEntity.ok(tasks);
    }
    
    /**
     * 根据状态查找任务列表
     */
    @GetMapping("/status/{status}")
    public ResponseEntity<List<TaskDTO>> findTasksByStatus(@PathVariable TaskStatus status) {
        try {
            List<TaskDTO> tasks = taskApplicationService.findTasksByStatus(status);
            return ResponseEntity.ok(tasks);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 根据层级查找任务列表
     */
    @GetMapping("/level/{level}")
    public ResponseEntity<List<TaskDTO>> findTasksByLevel(@PathVariable TaskLevel level) {
        try {
            List<TaskDTO> tasks = taskApplicationService.findTasksByLevel(level);
            return ResponseEntity.ok(tasks);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 获取任务统计信息
     */
    @GetMapping("/statistics")
    public ResponseEntity<TaskStatisticsDTO> getTaskStatistics() {
        try {
            TaskStatisticsDTO statistics = taskApplicationService.getTaskStatistics();
            return ResponseEntity.ok(statistics);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 分页查询任务列表（支持筛选和排序）
     */
    @GetMapping
    public ResponseEntity<Page<TaskDTO>> findTasks(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(defaultValue = "id") String sortField,
            @RequestParam(defaultValue = "asc") String sortDirection,
            @RequestParam(required = false) TaskStatus status,
            @RequestParam(required = false) TaskPriority priority,
            @RequestParam(required = false) String assignee,
            @RequestParam(required = false) String requirement,
            @RequestParam(required = false) String taskId,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) Integer progressMin,
            @RequestParam(required = false) Integer progressMax) {
        
        try {
            // 创建排序对象
            Sort.Direction direction = "desc".equalsIgnoreCase(sortDirection) 
                ? Sort.Direction.DESC : Sort.Direction.ASC;
            Sort sort = Sort.by(direction, sortField);
            Pageable pageable = PageRequest.of(page, size, sort);
            
            // 构建筛选条件
            Map<String, Object> filters = new HashMap<>();
            if (status != null) filters.put("status", status);
            if (priority != null) filters.put("priority", priority);
            if (assignee != null && !assignee.trim().isEmpty()) filters.put("assignee", assignee.trim());
            if (requirement != null && !requirement.trim().isEmpty()) filters.put("requirement", requirement.trim());
            if (taskId != null && !taskId.trim().isEmpty()) filters.put("taskId", taskId.trim());
            if (title != null && !title.trim().isEmpty()) filters.put("title", title.trim());
            if (progressMin != null) filters.put("progressMin", progressMin);
            if (progressMax != null) filters.put("progressMax", progressMax);
            
            Page<TaskDTO> tasks = taskApplicationService.findTasksWithFilters(pageable, filters);
            return ResponseEntity.ok(tasks);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 查找所有任务（不分页）
     */
    @GetMapping("/all")
    public ResponseEntity<List<TaskDTO>> findAllTasks() {
        List<TaskDTO> tasks = taskApplicationService.findAllTasks();
        return ResponseEntity.ok(tasks);
    }
    
    /**
     * 查找所有子任务
     */
    @GetMapping("/{id}/subtasks")
    public ResponseEntity<List<TaskDTO>> findAllSubtasks(@PathVariable Long id) {
        List<TaskDTO> tasks = taskApplicationService.findAllSubTasks(id);
        return ResponseEntity.ok(tasks);
    }
    
    /**
     * 更新任务状态
     */
    @PatchMapping("/{id}/status")
    public ResponseEntity<?> updateTaskStatus(@PathVariable Long id, @RequestBody Map<String, String> request) {
        try {
            String statusStr = request.get("status");
            if (statusStr == null || statusStr.trim().isEmpty()) {
                return ResponseEntity.badRequest().body("状态不能为空");
            }
            
            TaskStatus newStatus = TaskStatus.valueOf(statusStr.toUpperCase());
            taskApplicationService.updateTaskStatus(id, newStatus);
            return ResponseEntity.ok().build();
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body("无效的状态值");
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 批量操作任务
     */
    @PatchMapping("/batch")
    public ResponseEntity<Void> batchUpdateTasks(@Valid @RequestBody BatchUpdateTaskCommand command) {
        try {
            taskApplicationService.batchUpdateTasks(command);
            return ResponseEntity.ok().build();
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
}